package com.example.service;

import com.example.entity.AiTalk;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.*;

@Service
public class AiTalkService
{
    private String theToken;
    public String talk(AiTalk aiTalk)
    {
        /**构造json*/
        String jsonString="{\"model\": \"deepseek-r1:7b\",\"messages\": [{\"role\": \"user\", \"content\": \"我希望你扮演"+aiTalk.getRole()+"\"},{\"role\": \"assistant\", \"content\": \"明白我会扮演的\"},{\"role\": \"user\", \"content\": \""+aiTalk.getTxtData()+"\"}],\"stream\": false}";
        JsonObject jsonObject = new Gson().fromJson(getReturn(jsonString),JsonObject.class);
        String endData=jsonObject.get("message").getAsJsonObject().get("content").getAsString();
        endData=endData.split("</think>")[1];
        return endData.trim();
    }
    /**获取返回值*/
    public String getReturn(String json)
    {
        String endData = "";
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(3000, TimeUnit.SECONDS);
        builder.readTimeout(60000, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();

        // 设置JSON的MediaType
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        // 创建RequestBody
        RequestBody body = RequestBody.create(json, JSON);

        // 构建Request
        Request request = new Request.Builder()
                .url("http://127.0.0.1:11434/api/chat")
                .post(body) // 设置POST请求体
                .addHeader("Content-Type", "application/json") // 可选，因为RequestBody已经设置了MediaType
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 获取响应体并返回
            endData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return endData;
    }
}
